package com.work.yshop.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.work.yshop.R;
import com.work.yshop.adapter.ArticleAdapter;
import com.work.yshop.model.Article;
import com.work.yshop.mvp.contract.ArticleContract;
import com.work.yshop.mvp.presenter.ArticlePresenter;
import com.work.yshop.ui.activity.AddArticleActivity;
import com.work.yshop.ui.activity.ArticleDetailActivity;
import com.work.yshop.ui.activity.SearchActivity;

import java.util.List;

/**
 * 农友圈Fragment - 卖家可以发布和查看农业相关帖子
 */
public class AgriCircleFragment extends Fragment implements ArticleContract.View {
    
    private static final String TAG = "AgriCircleFragment";
    private static final int REQUEST_ADD_ARTICLE = 100;
    
    private View rootView;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private View emptyView;
    private ArticleAdapter adapter;
    private ArticleContract.Presenter presenter;
    
    // 标签页相关控件
    private TextView tabFollow, tabLatest, tabMine;
    private View tabIndicatorFollow, tabIndicatorLatest, tabIndicatorMine;
    private ImageButton btnSearch, btnAdd;
    
    // 当前选中的标签页
    private int currentTabType = ArticleContract.TAB_LATEST;
    
    public static AgriCircleFragment newInstance() {
        return new AgriCircleFragment();
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_agri_circle, container, false);
        return rootView;
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 初始化Presenter
        presenter = new ArticlePresenter(requireContext());
        ((ArticlePresenter) presenter).attachView(this);
        
        initViews();
        setupListeners();
        
        // 加载文章列表，默认加载"最新"标签页
        presenter.loadArticlesByTab(currentTabType);
    }
    
    private void initViews() {
        recyclerView = rootView.findViewById(R.id.recycler_view);
        swipeRefreshLayout = rootView.findViewById(R.id.swipe_refresh);
        emptyView = rootView.findViewById(R.id.empty_view);
        
        // 标签页相关控件
        tabFollow = rootView.findViewById(R.id.tab_follow);
        tabLatest = rootView.findViewById(R.id.tab_latest);
        tabMine = rootView.findViewById(R.id.tab_mine);
        
        tabIndicatorFollow = rootView.findViewById(R.id.tab_indicator_follow);
        tabIndicatorLatest = rootView.findViewById(R.id.tab_indicator_latest);
        tabIndicatorMine = rootView.findViewById(R.id.tab_indicator_mine);
        
        btnSearch = rootView.findViewById(R.id.btn_search);
        btnAdd = rootView.findViewById(R.id.btn_add);
        
        // 设置RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new ArticleAdapter(getContext());
        recyclerView.setAdapter(adapter);
        
        // 设置下拉刷新颜色
        swipeRefreshLayout.setColorSchemeResources(R.color.green_500);
    }
    
    private void setupListeners() {
        // 标签页点击事件
        tabFollow.setOnClickListener(v -> switchTab(ArticleContract.TAB_FOLLOW));
        tabLatest.setOnClickListener(v -> switchTab(ArticleContract.TAB_LATEST));
        tabMine.setOnClickListener(v -> switchTab(ArticleContract.TAB_MINE));
        
        // 搜索按钮点击事件
        btnSearch.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), SearchActivity.class);
            startActivity(intent);
        });
        
        // 添加文章按钮点击事件
        btnAdd.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AddArticleActivity.class);
            startActivityForResult(intent, REQUEST_ADD_ARTICLE);
        });
        
        // 文章项点击事件
        adapter.setOnItemClickListener(position -> {
            // 获取文章对象并通知Presenter处理点击事件
            Article article = adapter.getItem(position);
            if (article != null) {
                presenter.onArticleClick(article);
            }
        });
        
        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener(() -> presenter.refreshArticlesByTab(currentTabType));
    }
    
    /**
     * 切换标签页
     */
    private void switchTab(int tabType) {
        if (currentTabType == tabType) {
            return;
        }
        
        currentTabType = tabType;
        
        // 更新标签页样式
        updateTabStyle();
        
        // 加载对应标签页的文章
        presenter.loadArticlesByTab(tabType);
    }
    
    /**
     * 更新标签页样式
     */
    private void updateTabStyle() {
        // 重置所有标签页样式
        tabFollow.setTextColor(getResources().getColor(R.color.text_secondary));
        tabLatest.setTextColor(getResources().getColor(R.color.text_secondary));
        tabMine.setTextColor(getResources().getColor(R.color.text_secondary));
        
        tabFollow.setTextSize(14);
        tabLatest.setTextSize(14);
        tabMine.setTextSize(14);
        
        tabFollow.setTypeface(null, android.graphics.Typeface.NORMAL);
        tabLatest.setTypeface(null, android.graphics.Typeface.NORMAL);
        tabMine.setTypeface(null, android.graphics.Typeface.NORMAL);
        
        tabIndicatorFollow.setBackgroundColor(getResources().getColor(android.R.color.transparent));
        tabIndicatorLatest.setBackgroundColor(getResources().getColor(android.R.color.transparent));
        tabIndicatorMine.setBackgroundColor(getResources().getColor(android.R.color.transparent));
        
        // 设置选中标签页样式
        switch (currentTabType) {
            case ArticleContract.TAB_FOLLOW:
                tabFollow.setTextColor(getResources().getColor(R.color.green_500));
                tabFollow.setTypeface(null, android.graphics.Typeface.BOLD);
                tabIndicatorFollow.setBackgroundColor(getResources().getColor(R.color.green_500));
                break;
                
            case ArticleContract.TAB_LATEST:
                tabLatest.setTextColor(getResources().getColor(R.color.green_500));
                tabLatest.setTypeface(null, android.graphics.Typeface.BOLD);
                tabIndicatorLatest.setBackgroundColor(getResources().getColor(R.color.green_500));
                break;
                
            case ArticleContract.TAB_MINE:
                tabMine.setTextColor(getResources().getColor(R.color.green_500));
                tabMine.setTypeface(null, android.graphics.Typeface.BOLD);
                tabIndicatorMine.setBackgroundColor(getResources().getColor(R.color.green_500));
                break;
        }
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_ADD_ARTICLE && resultCode == getActivity().RESULT_OK) {
            // 发布文章成功，刷新列表
            presenter.refreshArticlesByTab(currentTabType);
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (presenter != null) {
            presenter.detachView();
        }
        rootView = null;
    }
    
    // ArticleContract.View接口实现
    @Override
    public void showLoading() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(true);
        }
    }
    
    @Override
    public void hideLoading() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }
    
    @Override
    public void showArticles(List<Article> articles) {
        if (recyclerView != null && adapter != null) {
            recyclerView.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
            adapter.setData(articles);
        }
    }
    
    @Override
    public void showEmptyView() {
        if (recyclerView != null && emptyView != null) {
            recyclerView.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
        }
    }
    
    @Override
    public void showError(String message) {
        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void showPublishResult(boolean success, String message) {
        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public Context getContext() {
        return super.getContext();
    }
} 